<template>
  <div class="logs-container">
    <n-card title="系统日志管理">
      <!-- 过滤器 -->
      <div class="filter-section">
        <n-space>
          <n-select
            v-model:value="filter.level"
            placeholder="日志级别"
            clearable
            style="width: 120px"
            :options="levelOptions"
          />
          <n-input
            v-model:value="filter.module"
            placeholder="模块名称"
            clearable
            style="width: 150px"
          />
          <n-input
            v-model:value="filter.keyword"
            placeholder="关键词搜索"
            clearable
            style="width: 200px"
          />
          <n-button type="primary" @click="loadLogs">搜索</n-button>
          <n-button @click="clearFilter">重置</n-button>
          <n-button type="warning" @click="clearLogs">清空日志</n-button>
          <n-button type="info" @click="exportLogs">导出日志</n-button>
        </n-space>
      </div>

      <!-- 日志表格 -->
      <n-data-table
        :columns="columns"
        :data="logs"
        :loading="loading"
        :pagination="pagination"
        :scroll-x="1200"
        class="logs-table"
      />
    </n-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, h } from 'vue';
  import { invoke } from '@tauri-apps/api/core';
  import { save } from '@tauri-apps/plugin-dialog';
  import { NTag, NButton, useMessage } from 'naive-ui';
  import type { DataTableColumns } from 'naive-ui';

  interface LogEntry {
    timestamp: string;
    level: string;
    module: string;
    message: string;
    details?: string;
  }

  interface LogFilter {
    level?: string;
    module?: string;
    keyword?: string;
  }

  interface LogResponse {
    logs: LogEntry[];
    total: number;
    page: number;
    page_size: number;
  }

  const message = useMessage();
  const loading = ref(false);
  const logs = ref<LogEntry[]>([]);
  const filter = ref<LogFilter>({});

  const levelOptions = [
    { label: 'ERROR', value: 'ERROR' },
    { label: 'WARN', value: 'WARN' },
    { label: 'INFO', value: 'INFO' },
    { label: 'DEBUG', value: 'DEBUG' },
  ];

  const pagination = ref({
    page: 1,
    pageSize: 50,
    itemCount: 0,
    showSizePicker: true,
    pageSizes: [20, 50, 100],
    onChange: (page: number) => {
      pagination.value.page = page;
      loadLogs();
    },
    onUpdatePageSize: (pageSize: number) => {
      pagination.value.pageSize = pageSize;
      pagination.value.page = 1;
      loadLogs();
    },
  });

  const columns: DataTableColumns<LogEntry> = [
    {
      title: '时间',
      key: 'timestamp',
      width: 180,
      sorter: 'default',
    },
    {
      title: '级别',
      key: 'level',
      width: 80,
      render(row) {
        const type =
          row.level === 'ERROR'
            ? 'error'
            : row.level === 'WARN'
            ? 'warning'
            : row.level === 'INFO'
            ? 'info'
            : 'default';
        return h(NTag, { type }, { default: () => row.level });
      },
    },
    {
      title: '模块',
      key: 'module',
      width: 150,
      ellipsis: {
        tooltip: true,
      },
    },
    {
      title: '消息',
      key: 'message',
      width: 300,
      ellipsis: {
        tooltip: true,
      },
    },
    {
      title: '详情',
      key: 'details',
      width: 400,
      ellipsis: {
        tooltip: true,
      },
      render(row) {
        return row.details || '-';
      },
    },
    {
      title: '操作',
      key: 'actions',
      width: 100,
      render(row) {
        return h(
          NButton,
          {
            size: 'small',
            onClick: () => showLogDetail(row),
          },
          { default: () => '详情' }
        );
      },
    },
  ];

  // 加载日志
  const loadLogs = async () => {
    try {
      loading.value = true;
      const response: LogResponse = await invoke('get_logs', {
        filter: filter.value,
        page: pagination.value.page - 1,
        pageSize: pagination.value.pageSize,
      });

      logs.value = response.logs;
      pagination.value.itemCount = response.total;
    } catch (error) {
      message.error(`加载日志失败: ${error}`);
    } finally {
      loading.value = false;
    }
  };

  // 清空过滤器
  const clearFilter = () => {
    filter.value = {};
    pagination.value.page = 1;
    loadLogs();
  };

  // 清空日志
  const clearLogs = async () => {
    try {
      await invoke('clear_logs');
      message.success('日志已清空');
      loadLogs();
    } catch (error) {
      message.error(`清空日志失败: ${error}`);
    }
  };

  // 导出日志
  const exportLogs = async () => {
    try {
      const filePath = await save({
        filters: [
          {
            name: 'Log Files',
            extensions: ['log', 'txt'],
          },
        ],
        defaultPath: `app-logs-${new Date().toISOString().split('T')[0]}.log`,
      });

      if (filePath) {
        await invoke('export_logs', { exportPath: filePath });
        message.success('日志导出成功');
      }
    } catch (error) {
      message.error(`导出日志失败: ${error}`);
    }
  };

  // 显示日志详情
  const showLogDetail = (log: LogEntry) => {
    // 可以实现一个详情弹窗
    console.log('Log detail:', log);
  };

  onMounted(() => {
    loadLogs();
  });
</script>

<style scoped>
  .logs-container {
    padding: 16px;
  }

  .filter-section {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }

  .logs-table {
    margin-top: 16px;
  }
</style>